import json

class person(object):
	def __init__(self,name,age,sex):
			self.name=  name
			self.age = age
			self.sex  = sex
	def __repr__(self):
			return "name: %s\nage: %d\n" %(self.name,self.age)

def object2dict(obj):
	d= {}
	d['__class__'] = obj.__class__.__name__
	d['__module__'] = obj.__module__
	d.update(obj.__dict__)
	return d 

def dict2object(d):
	if '__class__ 'in d:
		class_name = d.pop('__class__')
		moudle_name = d.pop('__module__')
		moudle = __import__(moudle_name)
		class_ =  getattr(moudle,class_name)
		args = dict((key.encode('ascii'),value) for key,value in d.items())
		inst = class_(**args)
	else:
		inst = d
	return d

	
if __name__ == "__main__":
	person1 = person("qingluan",18)
	print person1
	d = object2dict(person1)
	print type(d),d

	o =  dict2object(d)
	print type(o) , o

	dump = json.dumps(person1,default=object2dict)
	print "dump",dump

	load = json.loads(dump,object_hook = dict2object)
	print load


